"""
@author:liazylee
@license: Apache Licence
@time: 2022/2/23 15:37
@contact: li233111@gmail.com
# code is far away from bugs with the god animal protecting
    I love animals. They taste delicious.
              ┏┓      ┏┓
            ┏┛┻━━━┛┻┓
            ┃      ☃      ┃
            ┃  ┳┛  ┗┳  ┃
            ┃      ┻      ┃
            ┗━┓      ┏━┛
                ┃      ┗━━━┓
                ┃  神兽保佑    ┣┓
                ┃　永无BUG！   ┏┛
                ┗┓┓┏━┳┓┏┛
                  ┃┫┫  ┃┫┫
                  ┗┻┛  ┗┻┛
"""
from django.contrib import admin  # noqa
from django.http import HttpResponse

from alipay_sdk.helper import trade_refund
from alipay_sdk.models import CallBackRecord
from user_info.models import RoomOrder


@admin.register(CallBackRecord)
class CallBackRecordAdmin(admin.ModelAdmin):
    list_display = ('id', 'subject', 'receipt_amount', 'out_trade_no')
    search_fields = ('subject', 'out_trade_no')
    # 退款功能
    actions = ['refund', 'export_csv']

    def export_csv(self, request, queryset):
        import csv
        from io import StringIO
        f = StringIO()
        writer = csv.writer(f)
        writer.writerow(['订单号', '支付宝账号', '支付金额', '支付时间', '交易流水号', '状态'])
        for obj in queryset:
            writer.writerow([obj.out_trade_no, obj.buyer_logon_id, obj.receipt_amount, obj.gmt_payment, obj.trade_no,
                             obj.trade_status])
        f.seek(0)
        response = HttpResponse(f, content_type='application/csv')
        response['Content-Disposition'] = 'attachment; filename="call_back_record.csv"'
        return response

    def refund(self, request, queryset):
        for queryset_item in queryset:
            order_id = queryset_item.out_trade_no
            price = queryset_item.receipt_amount
            if trade_refund(order_id, price):
                self.message_user(request, f'{queryset_item.buyer_logon_id} 退款{queryset_item.receipt_amount}元成功')
                # 修改订单状态
                _ = RoomOrder.objects.filter(order_id=order_id).update(is_canceled=True)
            else:
                self.message_user(request, f'{queryset_item.buyer_logon_id} 退款{queryset_item.receipt_amount}元失败')

    refund.short_description = '退款'
    export_csv.short_description = '导出支付宝记录'
